package chaoyue.study.factory;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

/**
 * 添加自定义网关过滤
 * 往header中添加ThraceId
 */
@Slf4j
@Component
public class TraceGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
    @Override
    public GatewayFilter apply(NameValueConfig config) {
        return (exchange, chain) -> {
            // 重新封装request
            ServerHttpRequest changedRequest = exchange.getRequest()
                    .mutate()
                    .header("traceId", UUID.randomUUID().toString())
                    .build();
            // 将重新封装的request放入到上下文中
            ServerWebExchange changedExchange = exchange.mutate()
                    .request(changedRequest).build();
            // 将上下文设置到过滤器链中
            log.info("前置任务执行完成。。。");
            exchange.getAttributes().put("myParam", "param add by pre task");// 添加属性
            return chain.filter(changedExchange).then(
                    Mono.fromRunnable(() -> {
                        // 后置任务，回程的时候执行
                        log.info("后置任务执行完成 获取参数:{}", exchange.getAttribute("myParam").toString());
                    }));
        };
    }
}
